#include "BaseInc.h"
#include "Texture.h"

bool Texture::LoadTexture(const char* path)
{
	FREE_IMAGE_FORMAT fifmt = FreeImage_GetFileType(path, 0);   //Get file type
	if (fifmt == FIF_UNKNOWN)
	{
		fifmt = FreeImage_GetFIFFromFilename(path);
		if (fifmt == FIF_UNKNOWN)
			return false;
	}

	FIBITMAP* dib = FreeImage_Load(fifmt, path, 0);
	dib = FreeImage_ConvertTo24Bits(dib);   //convert to 24 bits

	int width = FreeImage_GetWidth(dib);    //get the width of texture
	int height = FreeImage_GetHeight(dib);  //height
	BYTE* pixels = (BYTE*)FreeImage_GetBits(dib); //pixels
	if (!pixels)
		return false;
	glGenTextures(1, &texId);
	glBindTexture(GL_TEXTURE_2D, texId);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	//generate the texture image
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0
		, GL_BGR_EXT, GL_UNSIGNED_BYTE, pixels);  //transfer into OpenGL
	//glGenerateMipmap(GL_TEXTURE_2D);
	FreeImage_Unload(dib);   //release the memory
	return true;

}

